<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="form.name"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="form.age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="form.gender" >
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button  @click="Onclick">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr  v-for="item in arr" :key="item.id">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="remove(item.id)">删除</button>
            <button @click="showEdit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return {
      arr: [
        {id:1, name:'tom',age:18,gender:"男"},
        {id:2, name:'lina',age:18,gender:"女"},
        {id:3, name:'lee',age:18,gender:"男"}
        ],

    form:{
      age:'',
      gender:'',
      name:'',
    },
    }
  },
  methods:{
    Onclick(){
     if(
      this.form.name ==='' ||
      this.form.age===''||
      this.form.gender===''){
        return alert('输入框不能为空')
    }
    if(!this.form.id){
      // 添加
      // slice 可以替换内容
      // 如果数组是空的，Id就直接设置成1，如果数组不是空的，就把id设置成数组最后一项的id的基础上加1
      const id=this.arr.length===0 ? 1:this.arr.slice (-1)[0].id+1;
      this.form.id=id;
      this.arr.push({...this.form})
    }else{
      // 编辑
      // 根据id找索引
      const index =this.arr.findIndex((item)=>item.id===this.form.id)

      this.arr.splice(index,1,{...this.form}); 
      this.form.id =''
    }
    // 输入完输入框内容设置为空
    this.form.name =this.form.age =this.form.id = this.form.gender =''
  },
  // 删除
  remove(id){
    const index =this.arr.findIndex((item)=>item.id === id);
    this.arr.splice(index,1)
  },
  // 编辑
  showEdit(id){
    const obj =this.arr.find((item) =>item.id === id);
    this.form = {...obj}
  }
  }
}

</script>